import * as echarts from '../../components/ec-canvas/echarts';
const request = require('../../utils/request');

Page({
  data: {
    ecLine: {
      lazyLoad: true
    },
    ecPie: {
      lazyLoad: true
    },
    ecCalendar: {
      lazyLoad: true
    },
    categoryData: [
      { value: 35, name: '编程开发' },
      { value: 25, name: '设计创作' },
      { value: 20, name: '数据分析' },
      { value: 15, name: '人工智能' },
      { value: 5, name: '其他课程' }
    ],
    calendarRange: null
  },

  async onReady() {
    try {
      wx.showLoading({
        title: '加载中'
      });

      // 获取当前用户ID
      const app = getApp();
      if (!app.globalData.isLoggedIn || !app.globalData.userInfo) {
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        });
        return;
      }

      const userId = app.globalData.userInfo.id;
      
      // 初始化日历范围为当前月
      this.setData({
        calendarRange: {
          end: new Date(),
          months: 0
        }
      });

      // 获取图表组件引用
      this.lineChart = this.selectComponent('#mychart-dom-line');
      this.pieChart = this.selectComponent('#mychart-dom-pie');
      this.calendarChart = this.selectComponent('#mychart-dom-calendar');

      console.log('组件引用:', {
        lineChart: !!this.lineChart,
        pieChart: !!this.pieChart,
        calendarChart: !!this.calendarChart
      });

      // 初始化图表
      await this.initCharts();

      // 获取报表数据
      const response = await request({
        url: '/api/report/overview',
        method: 'GET',
        data: { userId }
      });

      console.log('收到报表数据:', response?.data);

      if (response?.data) {
        // 更新图表
        this.updateCharts(response.data);
      }

      wx.hideLoading();
    } catch (err) {
      console.error('初始化失败:', err);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
      wx.hideLoading();
    }
  },

  // 获取日历图配置
  getCalendarOption() {
    return {
      tooltip: {
        formatter: function(params) {
          const date = new Date(params.value[0]);
          const dateStr = `${date.getFullYear()}年${date.getMonth()+1}月${date.getDate()}日`;
          const value = params.value[1];
          const valueText = value > 0 ? `完成课程：${value}节` : '没有课程记录';
          return `${dateStr}\n${valueText}`;
        },
        backgroundColor: 'rgba(50,50,50,0.8)',
        textStyle: {
          color: '#fff'
        },
        padding: [8, 10]
      },
      visualMap: {
        min: 0,
        max: 5,
        calculable: true,
        orient: 'horizontal',
        left: 'center',
        bottom: 20,
        inRange: {
          color: ['#ebedf0', '#c6e48b', '#7bc96f', '#239a3b', '#196127']  // GitHub风格的颜色
        },
        text: ['高', '低'],
        textStyle: {
          color: '#666'
        }
      },
      calendar: {
        top: 25,
        left: 50,
        right: 30,
        cellSize: ['auto', 24],
        range: this.getCalendarRange(),
        itemStyle: {
          borderWidth: 0.5
        },
        yearLabel: { show: false },
        dayLabel: {
          firstDay: 1,
          nameMap: 'cn'
        },
        monthLabel: {
          show: true,
          nameMap: 'cn',
          formatter: '{MM}月',
          color: '#666',
          fontSize: 12,
          position: 'end'
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: '#ddd',
            width: 1.5,
            type: 'solid'
          }
        }
      },
      series: {
        type: 'heatmap',
        coordinateSystem: 'calendar',
        data: []
      }
    };
  },

  // 获取日历显示范围
  getCalendarRange() {
    // 格式化日期为YYYY-MM-DD字符串
    const formatDate = (date) => {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    };

    // 使用当前月份
    const now = new Date();
    
    // 如果有日历范围设置，则使用设置的月份
    if (this.data.calendarRange) {
      const monthsOffset = this.data.calendarRange.months || 0;
      const targetDate = new Date();
      targetDate.setMonth(targetDate.getMonth() + monthsOffset);
      
      // 获取当月第一天
      const firstDay = new Date(targetDate.getFullYear(), targetDate.getMonth(), 1);
      // 获取当月最后一天
      const lastDay = new Date(targetDate.getFullYear(), targetDate.getMonth() + 1, 0);
      
      return [formatDate(firstDay), formatDate(lastDay)];
    }
    
    // 默认返回当前月份的第一天和最后一天
    const firstDay = new Date(now.getFullYear(), now.getMonth(), 1);
    const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0);
    
    return [formatDate(firstDay), formatDate(lastDay)];
  },
  
  // 切换日历显示范围
  changeCalendarRange(direction) {
    // 获取当前日期范围
    const currentRange = this.data.calendarRange || {
      end: new Date(),
      months: 0
    };
    
    let newEnd = new Date(currentRange.end);
    
    // 根据方向前进或后退一个月
    if (direction === 'next') {
      newEnd.setMonth(newEnd.getMonth() + 1);
      currentRange.months += 1;
    } else if (direction === 'prev') {
      newEnd.setMonth(newEnd.getMonth() - 1);
      currentRange.months -= 1;
    } else if (direction === 'current') {
      newEnd = new Date(); // 回到当前月
      currentRange.months = 0;
    }
    
    // 更新范围
    this.setData({
      calendarRange: {
        end: newEnd,
        months: currentRange.months
      }
    }, () => {
      // 重新请求数据并刷新图表
      this.reloadCalendarData();
    });
  },
  
  // 重新加载日历数据
  async reloadCalendarData() {
    try {
      wx.showLoading({
        title: '加载数据中'
      });
      
      // 获取当前范围
      const range = this.getCalendarRange();
      const startDate = range[0];
      const endDate = range[1];
      
      console.log('请求日历数据范围:', startDate, '至', endDate);
      
      // 获取当前用户ID
      const app = getApp();
      const userId = app.globalData.userInfo.id;
      
      // 根据新范围请求数据
      const response = await request({
        url: '/api/report/calendar',
        method: 'GET',
        data: { 
          userId,
          startDate,
          endDate
        }
      });
      
      if (response && response.data) {
        console.log('收到日历数据:', response.data);
        // 确保响应中包含日历数据
        const calendarData = response.data.calendar || response.data;
        
        // 确认数据结构并进行转换
        let formattedData = [];
        if (Array.isArray(calendarData)) {
          formattedData = calendarData.map(item => {
            // 如果已经是[date, value]格式，直接返回
            if (Array.isArray(item)) {
              return item;
            }
            // 如果是{date, value}对象，转换为数组
            return [item.date, item.value || 0];
          });
        }
        
        console.log('格式化后的日历数据:', formattedData);
        // 更新日历图
        this.updateCalendarChart(formattedData);
      } else {
        console.warn('未收到有效的日历数据');
      }
      
      wx.hideLoading();
    } catch (err) {
      console.error('加载日历数据失败:', err);
      wx.hideLoading();
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    }
  },
  
  // 更新日历图表
  updateCalendarChart(calendarData) {
    console.log('正在更新日历图表', calendarData);
    try {
      // 确保图表已初始化
      if (!this.calendarChartComponent) {
        console.warn('日历图表未初始化');
        return;
      }

      // 确保日历数据有效
      if (!calendarData || !Array.isArray(calendarData) || calendarData.length === 0) {
        console.warn('日历数据为空或格式不正确', calendarData);
        return;
      }

      // 获取日历显示范围
      const [startDate, endDate] = this.getCalendarRange();
      console.log('日历范围:', startDate, '至', endDate);

      // 处理数据格式，确保数据是[日期, 值]格式
      const formattedData = calendarData.map(item => {
        // 如果数据已经是数组格式，直接返回
        if (Array.isArray(item)) {
          return item;
        }
        // 如果是对象格式，转换为数组格式
        if (item && item.date) {
          return [item.date, item.value || 0];
        }
        return null;
      }).filter(item => item !== null);

      // 创建完整的图表配置
      const option = this.getCalendarOption();
      
      // 更新日期范围和数据
      option.calendar.range = [startDate, endDate];
      option.series = [{
        type: 'heatmap',
        coordinateSystem: 'calendar',
        data: formattedData
      }];

      // 使用图表实例更新
      this.calendarChartComponent.setOption(option);
      console.log('日历图表更新成功');
    } catch (error) {
      console.error('更新日历图表失败:', error);
    }
  },

  // 获取折线图配置
  getLineOption() {
    return {
      tooltip: {
        trigger: 'axis',
        formatter: function(params) {
          const courseData = params[0];
          const countData = params[1];
          return `${courseData.axisValue}
                  完成课程：${countData.value}节
                  课程数量：${courseData.value}个`;
        }
      },
      legend: {
        data: ['不同课程数', '完成课程数'],
        bottom: 0
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: []
      },
      yAxis: {
        type: 'value',
        name: '数量'
      },
      series: [{
        name: '不同课程数',
        type: 'line',
        smooth: true,
        data: [],
        stack: 'Total',
        areaStyle: {
          opacity: 0.3
        },
        itemStyle: {
          color: '#409EFF'
        }
      }, {
        name: '完成课程数',
        type: 'line',
        smooth: true,
        data: [],
        stack: 'Total',
        areaStyle: {
          opacity: 0.3
        },
        itemStyle: {
          color: '#67C23A'
        }
      }]
    };
  },

  updateCharts(data) {
    const { courses, categories, calendar } = data;
    
    // 更新折线图
    if (this.lineChartComponent) {
      try {
        const lineData = this.processLineData(courses);
        
        const lineOption = this.getLineOption();
        lineOption.xAxis.data = lineData.dates;
        lineOption.series[0].data = lineData.courseCounts;
        lineOption.series[1].data = lineData.counts;
        
        this.lineChartComponent.setOption(lineOption);
      } catch (error) {
        console.error('折线图更新失败:', error);
      }
    }

    // 更新饼图
    if (this.pieChartComponent) {
      try {
        const pieData = this.processPieData(categories);
        
        const option = {
          series: [{
            type: 'pie',
            radius: ['50%', '70%'],
            label: {
              show: true,
              position: 'outside',
              formatter: '{b}\n{d}%',
              fontSize: 12
            },
            data: pieData
          }]
        };
        
        this.pieChartComponent.setOption(option);
      } catch (error) {
        console.error('[饼图] 更新失败:', error);
      }
    } else {
      console.error('[饼图] 组件未初始化');
    }

    // 如果有日历数据，更新日历图
    if (calendar && Array.isArray(calendar) && calendar.length > 0) {
      if (this.calendarChartComponent) {
        console.log('通过updateCharts更新日历图表');
        this.updateCalendarChart(calendar);
      } else {
        console.warn('日历图表未初始化或图表实例不存在');
      }
    } else {
      console.warn('未收到有效的日历数据');
    }
  },
  
  initCharts: async function() {
    try {
      let components = [];
      
      // 折线图初始化
      try {
        const lineComponent = await this.initLineChart();
        components.push(lineComponent);
      } catch (error) {
        console.error('折线图初始化失败:', error);
        components.push(null);
      }

      // 饼图初始化
      try {
        const pieComponent = await this.initPieChart();
        components.push(pieComponent);
      } catch (error) {
        console.error('[饼图] 初始化失败:', error);
        components.push(null);
      }

      // 日历图初始化
      try {
        const calendarComponent = await this.initCalendarChart();
        components.push(calendarComponent);
      } catch (error) {
        console.error('日历图初始化失败:', error);
        components.push(null);
      }

      // 保存初始化后的组件实例
      [this.lineChartComponent, this.pieChartComponent, this.calendarChartComponent] = components;

      // 允许部分图表初始化失败
      return true;

    } catch (error) {
      console.error('图表初始化失败:', error);
      return false;
    }
  },

  // 分离各个图表的初始化方法
  async initPieChart() {
    if (!this.pieChart) return null;
    
    return new Promise((resolve) => {
      this.pieChart.init((canvas, width, height, dpr) => {
        try {
          const chart = echarts.init(canvas, null, {
            width: width,
            height: height,
            devicePixelRatio: dpr
          });
          const option = this.getPieOption();
          chart.setOption(option);
          resolve(chart);
          return chart;
        } catch (error) {
          console.error('[饼图] 创建实例失败:', error);
          resolve(null);
          return null;
        }
      });
    });
  },

  // 获取饼图配置
  getPieOption() {
    return {
      color: ['#3A7FED', '#36CBCB', '#4ECB73', '#FBD437', '#F2637B'],
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c}节 ({d}%)'
      },
      series: [{
        name: '课程分布',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: true,
          position: 'outside',
          formatter: '{b}\n{d}%',
          fontSize: 12
        },
        labelLine: {
          show: true
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 14,
            fontWeight: 'bold'
          }
        },
        data: []  // 初始为空，等待API数据
      }]
    };
  },

  // 处理折线图数据
  processLineData(courses) {
    // 确保courses是数组
    if (!Array.isArray(courses)) {
      console.error('课程数据格式错误:', courses);
      return { dates: [], courseCounts: [], counts: [] };
    }

    // 按日期排序（日期格式已经是 MM-DD）
    const sortedCourses = [...courses].sort((a, b) => {
      // 为了正确比较，将日期转换为完整格式
      const yearPrefix = new Date().getFullYear() + '-';
      return new Date(yearPrefix + a.date) - new Date(yearPrefix + b.date);
    });
    
    const dates = sortedCourses.map(item => item.date); // 直接使用 MM-DD 格式
    const courseCounts = sortedCourses.map(item => Number(item.course_count));
    const counts = sortedCourses.map(item => Number(item.count));
    
    return {
      dates,
      courseCounts,
      counts
    };
  },

  // 处理饼图数据
  processPieData(categories) {
    if (!Array.isArray(categories)) {
      console.error('[饼图] 数据格式错误:', categories);
      return [];
    }
    
    const processedData = categories.map(item => ({
      value: Number(item.count),
      name: item.category,
      percentage: Number(item.percentage)
    }));
    
    return processedData;
  },

  // 添加折线图初始化方法
  async initLineChart() {
    if (!this.lineChart) return null;
    
    return new Promise((resolve) => {
      this.lineChart.init((canvas, width, height, dpr) => {
        try {
          const chart = echarts.init(canvas, null, {
            width: width,
            height: height,
            devicePixelRatio: dpr
          });
          const option = this.getLineOption();
          chart.setOption(option);
          resolve(chart);
          return chart;
        } catch (error) {
          console.error('折线图创建实例失败:', error);
          resolve(null);
          return null;
        }
      });
    });
  },

  // 添加日历图初始化方法
  async initCalendarChart() {
    console.log('正在初始化日历图表');
    if (!this.calendarChart) {
      console.warn('日历图表组件不存在');
      return null;
    }
    
    return new Promise((resolve) => {
      this.calendarChart.init((canvas, width, height, dpr) => {
        try {
          console.log('日历图表Canvas初始化', width, height, dpr);
          const chart = echarts.init(canvas, null, {
            width: width,
            height: height,
            devicePixelRatio: dpr
          });
          
          // 获取初始配置
          const option = this.getCalendarOption();
          
          // 设置初始空数据
          chart.setOption(option);
          
          // 保存图表实例
          this.calendarChartComponent = chart;
          
          console.log('日历图表初始化成功');
          resolve(chart);
          return chart;
        } catch (error) {
          console.error('日历图创建实例失败:', error);
          resolve(null);
          return null;
        }
      });
    });
  },

  // 添加生成模拟数据的方法
  generateMockCalendarData() {
    const end = new Date();
    const start = new Date();
    start.setDate(end.getDate() - 29);
    
    const mockData = [];
    const currentDate = new Date(start);
    
    while (currentDate <= end) {
      // 生成0-5之间的随机数，模拟每天完成的课程数
      const value = Math.floor(Math.random() * 6);
      mockData.push([
        currentDate.toISOString().split('T')[0],  // 日期格式：YYYY-MM-DD
        value
      ]);
      currentDate.setDate(currentDate.getDate() + 1);
    }
    
    // 添加一些特定的高值，使热力图更有变化
    const randomHighDays = 5;
    for (let i = 0; i < randomHighDays; i++) {
      const randomIndex = Math.floor(Math.random() * mockData.length);
      mockData[randomIndex][1] = 5;  // 设置为最高值
    }
    
    return mockData;
  },

  onLoad: function (options) {
    // 空实现，不再调用不存在的initData函数
  },

  // 处理TabBar点击事件
  onTabItemTap(item) {
    console.log('TabBar点击事件 - 学习报告:', item);
    const app = getApp();
    app.handleTabItemTap(this, item);
  },

  // 上一月按钮点击处理
  calendarPrevMonth() {
    this.changeCalendarRange('prev');
  },
  
  // 当前月按钮点击处理
  calendarCurrentMonth() {
    this.changeCalendarRange('current');
  },
  
  // 下一月按钮点击处理
  calendarNextMonth() {
    this.changeCalendarRange('next');
  },
});
